<template>
  <div class="art-container" ref="parent" @click="showMenu = false">
    <div class="art-top">
      <div class="art-search">
        <el-row :gutter="20">
          <el-col :span="4">
            <el-input
              placeholder="请输入关键字"
              v-model="queryParams.key"
              @keyup.native.enter="search"
              size="small"
              @clear="search"
              clearable
            ></el-input>
          </el-col>
          <el-col :span="4">
            <el-select
              v-model="queryParams.type"
              clearable
              @change="typeChange"
              class="search-select"
              placeholder="请选择文章类型"
              size="small"
            >
              <el-option
                v-for="item in articleTypes"
                :key="item.data_id"
                :label="item.series_name"
                :value="item.data_id"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select
              v-model="queryParams.open"
              clearable
              placeholder="是否公开"
              size="small"
              class="search-select"
              @change="typeChange"
            >
              <el-option
                v-for="item in isOpens"
                :key="item.data_id"
                :label="item.name"
                :value="item.data_id"
              ></el-option>
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-date-picker
              v-model="queryParams.min_create_time"
              type="date"
              size="small"
              placeholder="开始日期"
              style="margin-left: 10px"
              @change="typeChange"
              value-format="yyyy-MM-dd HH:mm:ss"
            ></el-date-picker>
          </el-col>
          <el-col :span="4" style="text-align: right">
            <el-date-picker
              v-model="queryParams.max_create_time"
              type="date"
              size="small"
              placeholder="结束日期"
              style="margin-left: 10px"
              @change="typeChange"
              value-format="yyyy-MM-dd HH:mm:ss"
            ></el-date-picker>
          </el-col>
          <el-col :span="4">
            <div class="art-btn"><el-button type="primary" size="small" @click="editor = true">新增</el-button></div>
          </el-col>
        </el-row>
      </div>
    </div>

    <el-scrollbar style="height: calc(100vh - 190px)" class="scrollbar" id="scroll-bar">
      <el-table :data="list" @row-contextmenu="contextMenu">
        <el-table-column label="标题" prop="title"></el-table-column>
        <el-table-column label="阅读量" prop="read_count"></el-table-column>

        <el-table-column label="文章类型" prop="type">
          <template slot-scope="scope">
            {{ scope.row.type == 1 ? '普通文章' : '专题文章' }}
          </template>
        </el-table-column>
        <el-table-column label="文章图片">
          <template slot-scope="scope">
            <el-image
              v-if="scope.row.show_url_list.length"
              style="width: 100px; height: 40px"
              :src="scope.row.show_url_list[0]"
              :preview-src-list="scope.row.show_url_list"
              fit="cover"
            ></el-image>
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>

        <el-table-column label="作者" prop="author"></el-table-column>
        <el-table-column label="发布时间" prop="create_time"></el-table-column>
        <el-table-column label="操作" width="420">
          <template slot-scope="scope">
            <el-button type="primary" @click="onShowDrawer(scope.row)" size="mini">详情</el-button>
            <el-button type="primary" @click="updArticle(scope.row)" size="mini">修改</el-button>
            <el-button type="danger" @click="delArticle(scope.row.data_id)" size="mini">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>

    <paging ref="page" :func="getList"></paging>

    <el-dialog
      fullscreen
      title="编辑文章"
      :visible.sync="editor"
      :show-close="false"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <el-form :model="dataParams" :rules="rules" ref="dataParams" label-width="120px" class="demo-dataParams">
        <el-form-item label="标题" prop="title">
          <el-input v-model="dataParams.title" placeholder="请输入作品名"></el-input>
        </el-form-item>
        <el-form-item label="文章类型" prop="type">
          <el-select v-model="dataParams.type" class="search-select" placeholder="文章类型" size="small">
            <el-option
              v-for="item in articleTypes"
              :key="item.data_id"
              :label="item.series_name"
              :value="item.data_id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <wangEditor v-if="editor" :content="obj.content" ref="editor" :key="obj.data_id"></wangEditor>
        </el-form-item>
        <el-form-item label="是否公开" prop="open">
          <el-select v-model="dataParams.open" class="search-select" placeholder="是否公开" size="small">
            <el-option v-for="item in isOpens" :key="item.data_id" :label="item.name" :value="item.data_id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editor = false">取 消</el-button>
        <el-button type="primary" @click="saveArticle">保 存</el-button>
      </span>
    </el-dialog>

    <el-drawer :title="obj.title" :visible.sync="isShowDrawer" direction="rtl" size="50%">
      <div v-dompurify-html="obj.content" style="padding: 20px"></div>
    </el-drawer>
    <div class="menu" ref="menu" v-show="showMenu">
      <div @click="move('up')">前移</div>
      <div @click="move('down')">后移</div>
      <div @click="move('top')">置顶</div>
      <div @click="move('bottom')">置底</div>
    </div>
  </div>
</template>

<script>
  import paging from '@/components/paging';
  import articleManage from '@/api/article';
  import wangEditor from '@/components/wangEditor.vue';
  import { qiniuUploadFile } from '@/utils/QiniuUpload';

  export default {
    components: {
      paging,
      wangEditor,
    },
    watch: {
      editor(n, o) {
        if (!n) {
          this.dataParams = { open: 1, type: 1 };
          this.obj = {};
        }
      },
    },
    data() {
      return {
        dataList: [],
        queryParams: {
          key: '',
          type: '',
          open: '',
          min_create_time: '',
          max_create_time: '',
        },
        optionValue: 'all',
        articleTypes: [
          { series_name: '普通文章', data_id: 1 },
          { series_name: '专题文章', data_id: 2 },
        ],
        isOpens: [
          { name: '公开', data_id: 1 },
          { name: '不公开', data_id: 0 },
        ],
        typeList: [],
        list: [],
        editor: false,

        dataParams: {
          title: '',
          type: 1,
          open: 1,
          content: '',
          show_url_list: [],
        },
        obj: {},
        isShowDialog: false,
        isShowDrawer: false,
        rules: {
          title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
          type: [{ required: true, message: '请选择文章类型', trigger: 'change' }],
        },
        showMenu: false,
        menuId: '',
        resAttr: [],
        update: false,
      };
    },
    async mounted() {
      this.refresh();
    },
    computed: {
      type() {
        let res = this.resAttr.find((item) => {
          return item.data_id === this.obj.type;
        });
        return res?.name;
      },
      typeChild() {
        let res = this.resAttr.find((item) => {
          return item.data_id === this.obj.type_child;
        });
        return res?.name;
      },
    },
    methods: {
      async move(type) {
        await articleManage.moveArticle(this.menuId, 'move_' + type);
        this.showMenu = false;
        this.$refs.page.refresh();
      },
      contextMenu(r, column, e) {
        let rect = this.$refs.parent.getBoundingClientRect();
        this.$refs.menu.style.top = e.clientY - rect.top + 'px';
        this.$refs.menu.style.left = e.clientX - rect.left + 'px';
        this.showMenu = true;
        this.menuId = r.data_id;
        e.preventDefault();
      },
      refresh() {
        this.$refs.page.refresh();
      },
      search() {
        this.$refs.page.search();
      },
      typeChange() {
        this.$refs.page.refresh();
      },
      async artChange(id) {
        let typeRes = await typeManage.getTypeAttrs({ notPagination: true, art_id: id });
        this.typeList = typeRes.item_list.filter((item) => {
          return item.parent_id === -1 && item.child_item_list.length;
        });

        let obj = this.isOpens.find((item) => {
          return (item.data_id = id);
        });
        this.dataParams.art_name = obj.name;
      },
      getList(callback) {
        articleManage.getArticle(this.queryParams).then((res) => {
          let total = res.total_count;
          this.list = res.item_list;
          callback(this.list, total);
        });
      },
      async beforeAvatarUpload(file, id) {
        let res = await qiniuUploadFile(file, 'article');
        if (res) {
          await articleManage.updArt(id, { show_url_list: [res] });
          this.refresh();
        }

        // const formData = new FormData();
        // formData.append('上传的key值', file);
        // await artManage.setArtImage(id, formData);
        // this.refresh();
      },
      async beforeMapUpload(file, row) {
        let res = await qiniuUploadFile(file, 'article');
        if (res) {
          let url = res.key;
          let opus_id = await artManage.imageMap({
            image_list: [
              {
                image_src_url: url,
                image_src_type: 'local',
                image_name: url.split('/')[2],
                type: 1,
                access_type: 0,
                note: '',
              },
            ],
          });
          await artManage.updArt(row.data_id, { opus_id });
          this.refresh();
        }

        // const formData = new FormData();
        // formData.append('上传的key值', file);
        // let url = await artManage.uploadMap(formData);
        // let opus_id = await artManage.imageMap({
        //   image_list: [
        //     {
        //       image_src_url: url,
        //       image_src_type: 'local',
        //       image_name: url.split('/')[2],
        //       type: 1,
        //       access_type: 0,
        //       note: '',
        //     },
        //   ],
        // });
        // await artManage.updArt(row.data_id, { opus_id });
        // this.refresh();
      },
      onClose() {
        this.updId = '';
        this.dataParams = {
          name: '',
          comment: '',
          art_id: '',
          recommend: false, //是否推荐
          type: '', //类型
          art_name: '',
          is_sell: false,
          price_min: 0,
          price_max: 0,
          work_detail: '',
          work_explain: '',
        };
      },
      async getArticleInfo(data_id) {
        this.obj = await articleManage.getArticleInfo(data_id);
      },
      async onShowDrawer(row) {
        await this.getArticleInfo(row.data_id);
        this.isShowDrawer = true;
      },
      async onRecommend(row) {
        await artManage.updArt(row.data_id, { recommend: row.recommend });
        this.refresh();
      },
      async onIsSell(row) {
        await artManage.updArt(row.data_id, { is_sell: row.is_sell });
        this.refresh();
      },
      async updArticle(row) {
        await this.getArticleInfo(row.data_id);
        this.dataParams = this.obj;
        this.dataParams.open = 1;
        this.editor = true;
        this.update = true;
      },
      async delArticle(data_id) {
        this.$alert('是否确定删除该文章', '删除', {
          confirmButtonText: '确定',
          callback: async (action) => {
            if (action === 'confirm') {
              await articleManage.delArticle(data_id);
              this.refresh();
            }
          },
        });
      },
      saveArticle() {
        this.dataParams.show_url_list = this.$refs.editor.getImages().map((m) => m.src);
        this.dataParams.content = this.$refs.editor.getContent();

        if (this.update) {
          let data_id = this.dataParams.data_id;

          articleManage.updArticle(data_id, this.dataParams).then((res) => {
            this.editor = false;
            this.update = false;
            this.refresh();
          });
        } else {
          this.dataParams.author = this.$store.getters.userInfo.name;
          articleManage.createArticle(this.dataParams).then((res) => {
            this.editor = false;
            this.refresh();
          });
        }
      },
      async dialogConfirm() {
        this.$refs.dataParams.validate(async (valid) => {
          if (valid) {
            let res = null;

            let types = this.dataParams.type;

            let params = {
              name: this.dataParams.name,
              comment: this.dataParams.comment,
              art_id: this.dataParams.art_id,
              recommend: this.dataParams.recommend, //是否推荐
              type: types[0], //类型
              type_child: types[1],
              material: this.dataParams.material,
              art_name: this.dataParams.art_name,
              is_sell: this.dataParams.is_sell,
              price_min:
                this.dataParams.price_min > this.dataParams.price_max
                  ? Number(this.dataParams.price_max)
                  : Number(this.dataParams.price_min),
              price_max:
                this.dataParams.price_min > this.dataParams.price_max
                  ? Number(this.dataParams.price_min)
                  : Number(this.dataParams.price_max),
              work_detail: this.dataParams.work_detail,
              work_explain: this.dataParams.work_explain,
            };

            if (this.updId) {
              res = await artManage.updArt(this.updId, params);
            } else {
              res = await artManage.setArt(params);
            }
            if (res) {
              this.isShowDialog = false;
              this.refresh();
            }
          }
        });
      },
    },
  };
</script>

<style lang="less" scoped>
  .menu {
    position: absolute;
    top: 0;
    left: 0;
    background-color: white;
    border-radius: 10px;
    box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.3);
    overflow: hidden;
    z-index: 999;
    & > div {
      padding: 10px 40px;
      border-bottom: 1px solid #eee;
      &:last-child {
        border-bottom: none;
      }
      &:hover {
        cursor: pointer;
        background-color: #409eff;
        color: white;
      }
    }
  }
  .art-container {
    height: 100%;
    .art-top {
      // display: flex;
      // align-items: center;
      // justify-content: space-between;
      .art-search {
        // display: flex;
        .search-select {
          margin-left: 12px;
        }
        .search-data {
          display: flex;
          div {
            margin-left: 12px;
          }
        }

        ::v-deep(.el-input__inner) {
          width: 100%;
        }

        ::v-deep(.el-date-editor.el-input) {
          width: 100%;
        }
      }
    }
  }
  .item-price {
    ::v-deep .el-form-item__content {
      display: flex;
      .el-input {
        width: 120px;
        .el-input__inner {
          width: 120px;
        }
      }
    }
  }
  .show-detail {
    .detail-item {
      width: 100%;
      display: flex;
      height: 40px;
      line-height: 40px;
      .item-title {
        width: 120px;
        text-align: right;
      }
      .item-content {
        color: #72767b;
      }
    }
  }
</style>
